package net.hzlj.platform.enterprise;

import android.app.Application;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Vibrator;
import android.support.annotation.NonNull;

import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.beardedhen.androidbootstrap.TypefaceProvider;
import com.czt.mp3recorder.Mp3RecorderUtil;
import com.orhanobut.logger.Logger;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.beta.UpgradeInfo;
import com.tencent.bugly.crashreport.CrashReport;
import com.zhy.http.okhttp.log.LoggerInterceptor;

import net.hzlj.platform.enterprise.activity.HomeActivity;
import net.hzlj.platform.enterprise.activity.LoginActivity;
import net.hzlj.platform.enterprise.beans.UserBean;
import net.hzlj.platform.enterprise.beans.ui.Category;
import net.hzlj.platform.enterprise.beans.ui.Column;
import net.hzlj.platform.enterprise.common.Constant;
import net.hzlj.platform.enterprise.config.HttpConfig;
import net.hzlj.platform.enterprise.daemon.DaemonClient;
import net.hzlj.platform.enterprise.daemon.DaemonConfigurations;
import net.hzlj.platform.enterprise.exception.UncaughtException;
import net.hzlj.platform.enterprise.helper.ToastHelper;
import net.hzlj.platform.enterprise.utils.StringUtils;
import net.hzlj.rl.zhangjiajie.R;
import net.hzlj.platform.enterprise.receiver.DaemonReceiver;
import net.hzlj.platform.enterprise.receiver.MainReceiver;
import net.hzlj.platform.enterprise.service.DaemonService;
import net.hzlj.platform.enterprise.service.MainService;
import net.hzlj.platform.enterprise.utils.AppPreferencesUtils;
import net.hzlj.platform.enterprise.utils.CommonUtils;
import net.hzlj.platform.enterprise.utils.DateUtils;
import net.hzlj.platform.enterprise.utils.NetworkUtils;
import net.hzlj.platform.enterprise.utils.PreferencesUtils;
import net.hzlj.platform.enterprise.utils.log.Log;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import cn.finalteam.okhttpfinal.OkHttpFinal;
import cn.finalteam.okhttpfinal.OkHttpFinalConfiguration;
import okhttp3.Interceptor;

/**
 * @Description: 全局应用程序类：用于保存和调用全局应用配置及访问网络数据
 * @Author: Jason Zhang
 * @Date: 2016-8-22 15:49:47
 */
public class BootApp extends Application {

    private static final String TAG = BootApp.class.getSimpleName();

    public static BootApp mInstance;
    public static Context mAppContext;
    public static int NETWORK_TYPE = NetworkUtils.Type.WIFI;

    public static ArrayList<Column> COLUMNS = new ArrayList<Column>();
    public String[] mColumnNames;
    private static final int[] ICONS = new int[]{
            R.drawable.nav_tab_bottom_profile_selector
    };

    public static BootApp getInstance() {
        return mInstance;
    }

    public static Context getAppContext() {
        if (mAppContext == null)
            mAppContext = mInstance.getApplicationContext();
        return mAppContext;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        android.util.Log.i(TAG, "onCreate");
        mInstance = this;
        mAppContext = getApplicationContext();
        TypefaceProvider.registerDefaultIconSets();
        Mp3RecorderUtil.init(mAppContext, true);
        // 程序异常崩溃捕获
        Thread.setDefaultUncaughtExceptionHandler(UncaughtException.getInstance());
        mColumnNames = getResources().getStringArray(R.array.column_names);
        //初始化栏目
        initColumn();
        //初始化OkHttpFinal
        initOkHttpFinal();
        // 初始化日志
        Logger.init("HttpRequest");
        BootApp.getInstance().initCrashReport();
    }

    private void initOkHttpFinal() {
        List<Interceptor> interceptors = new ArrayList<>();
        interceptors.add(new LoggerInterceptor("HttpRequest"));

        OkHttpFinalConfiguration.Builder builder = new OkHttpFinalConfiguration.Builder()
                .setDebug(Constant.DEBUG)
                .setTimeout(300000)
                .setInterceptors(interceptors);
        OkHttpFinal.getInstance().init(builder.build());
    }

    //初始化栏目
    public void initColumn() {
        if (COLUMNS == null || COLUMNS.isEmpty()) {
            ArrayList<Column> columnObjects = new ArrayList<Column>();
            Column profile = new Column(Column.COLUMN_ID_PROFILE, mColumnNames[0], Column.COLUMN_TYPE_1,
                    new Category(Column.COLUMN_ID_PROFILE, Column.COLUMN_NAME_PROFILE), ICONS[0]);
            columnObjects.add(profile);
            BootApp.COLUMNS = columnObjects;
        }
    }

    public void initCrashReport() {
        CrashReport.UserStrategy userStrategy = new CrashReport.UserStrategy(mAppContext);
        userStrategy.setAppVersion(getResources().getString(R.string.app_name) + "_v" + CommonUtils.getVersionName(mAppContext));
        userStrategy.setAppChannel(Constant.Bugly.APP_CHANNEL);
        userStrategy.setDeviceID(CommonUtils.getDeviceID(mAppContext));
        userStrategy.setAppReportDelay(Constant.Bugly.APP_REPORT_DELAY);
        //设置升级策略
        /***
         * 自动初始化开关
         * true表示app启动自动初始化升级模块;
         * false不会自动初始化;
         * 开发者如果担心sdk初始化影响app启动速度，可以设置为false，在后面某个时刻手
         * 动调用Beta.init(getApplicationContext(),false);
         */
        Beta.autoInit = true;
        /***
         * 自动检查更新开关
         * true表示初始化时自动检查升级;
         * false表示不会自动检查升级,需要手动调用Beta.checkUpgrade()方法;
         */
        Beta.autoCheckUpgrade = true;
        /***
         * 升级检查周期设置
         * 设置升级检查周期为60s(默认检查周期为0s)，60s内SDK不重复向后台请求策略);
         */
        Beta.upgradeCheckPeriod = 60 * 1000;
        /***
         * 延迟初始化
         * 设置启动延时为1s（默认延时3s），APP启动1s后初始化SDK，避免影响APP启动速度;
         */
        Beta.initDelay = Constant.Bugly.INIT_DELAY;
        /***
         * 设置通知栏大图标
         * largeIconId为项目中的图片资源;
         */
        Beta.largeIconId = R.drawable.ic_launcher;
        /***
         * 设置状态栏小图标
         * smallIconId为项目中的图片资源id
         */
        Beta.smallIconId = R.drawable.ic_launcher;
        /***
         * 设置更新弹窗默认展示的banner
         * defaultBannerId为项目中的图片资源Id;
         * 当后台配置的banner拉取失败时显示此banner，默认不设置则展示“loading…“;
         */
        Beta.defaultBannerId = R.drawable.ic_launcher;
        /***
         * 设置sd卡的Download为更新资源存储目录
         */
//        Beta.storageDir = FileHelper.getApksDir();
        /***
         * 设置开启显示打断策略
         * 设置点击过确认的弹窗在App下次启动自动检查更新时会再次显示。
         */
        Beta.showInterruptedStrategy = true;
        /***
         * 添加可显示弹窗的Activity
         * 例如，只允许在LoginActivity上显示更新弹窗，其他activity上不显示弹窗; 如果不设
         * 置默认所有activity都可以显示弹窗。
         */
        Beta.canShowUpgradeActs.add(LoginActivity.class);
        Beta.canShowUpgradeActs.add(HomeActivity.class);
        /***
         * 设置使用自己的Activity
         * 可以通过这个选项设置自定义的弹窗Activity，如果设置了此项，固定布局id方式将不会生效。
         */
//		Beta.isCustomerActivity = true;
        /***
         * 设置自定义升级对话框UI布局
         * upgrade_dialog为项目的布局资源。
         * 注意：因为要保持接口统一，需要用户在指定控件按照以下方式设置tag，否则会影响您的正常使用：
         * 标题：beta_title，如：android:tag=”beta_title”
         * 升级信息：beta_upgrade_info 如： android:tag=”beta_upgrade_info”
         * 更新属性：beta_upgrade_feature 如： android:tag=”beta_upgrade_feature”
         * 取消按钮：beta_cancel_button 如：android:tag=”beta_cancel_button”
         * 确定按钮：beta_confirm_button 如：android:tag=”beta_confirm_button”
         */
//		Beta.upgradeDialogLayoutId = R.layout.upgrade_dialog;
        /***
         * 设置自定义tip弹窗UI布局
         * 注意：因为要保持接口统一，需要用户在指定控件按照以下方式设置tag，否则会影响您的正常使用：
         * 标题：beta_title，如：android:tag=”beta_title”
         * 提示信息：beta_tip_message 如： android:tag=”beta_tip_message”
         * 取消按钮：beta_cancel_button 如：android:tag=”beta_cancel_button”
         * 确定按钮：beta_confirm_button 如：android:tag=”beta_confirm_button”
         */
//		Beta.tipsDialogLayoutId = R.layout.tips_dialog;

        Bugly.init(mAppContext, Constant.Bugly.APP_ID, Constant.DEBUG, userStrategy);
        CrashReport.setUserId(CommonUtils.getDeviceID(mAppContext));
    }

    /***
     * 指定的天数是否是当前
     *
     * @param day
     * @return
     */
    public boolean isSameDayOfMonth(int day) {
        return DateUtils.getCurrentDay() == day;
    }

    /***
     * 检查网络是否连接
     *
     * @return
     */
    public static boolean netIsConnect(Context context) {
        checkNetwork();
        if (BootApp.NETWORK_TYPE == NetworkUtils.Type.DISABLED) {
            ToastHelper.newInstance().show(context, "网络不给力，请检查后重试");
            return false;
        }
        return true;
    }


    public static boolean isConnect() {
        checkNetwork();
        if (BootApp.NETWORK_TYPE == NetworkUtils.Type.DISABLED) {
            return false;
        }
        return true;
    }

    /**
     * 检查网络
     */
    public static void checkNetwork() {
        if (NetworkUtils.isConnected(BootApp.getAppContext())) {
            BootApp.NETWORK_TYPE = NetworkUtils.checkNetworkType(BootApp.getAppContext());
        } else {
            BootApp.NETWORK_TYPE = NetworkUtils.Type.DISABLED;
        }
        BootApp.getAppContext().sendBroadcast(new Intent(NetworkUtils.NETWORK_CHANGED));
    }

    //退出登录
    public void exitLogin() {
        AppPreferencesUtils.putObject(BootApp.getAppContext(), PreferencesUtils.KEY_USER_INFO, new UserBean());
        AppPreferencesUtils.putBoolean(BootApp.getAppContext(), PreferencesUtils.KEY_REMIND_PASSWORD, false);
        AppPreferencesUtils.putString(BootApp.getAppContext(), PreferencesUtils.KEY_USER_ACCOUNT, "");
    }

    /***
     * 更新用户信息之后，需要更新初始化人脸信息，防止进入照相机页面卡顿
     * @param type
     */
    public void updateFaceNative(int type) {
        if (type == HttpConfig.Type.LOGIN
                || type == HttpConfig.Type.CHANGE_PASSWORD
                || type == HttpConfig.Type.SELECT_RYMC_BY_ID) {
            //sendBroadcast(new Intent(Constant.Intent.ACTION_UPDATE_FACE_NATIVE));
        }
    }

    public boolean isLogin() {
        UserBean bean = AppPreferencesUtils.getObject(this, PreferencesUtils.KEY_USER_INFO, UserBean.class);
        if (bean != null) {
            android.util.Log.i(TAG, bean.toString());
        }
        return bean != null && bean.getId() != null && bean.getId() > 0;
    }

    public int getUserId() {
        UserBean bean = AppPreferencesUtils.getObject(this, PreferencesUtils.KEY_USER_INFO, UserBean.class);
        if (bean != null && bean.getId() != null && bean.getId() > 0) {
            return bean.getId();
        }
        return 0;
    }

    public String getUserTelephone(){
        UserBean bean = AppPreferencesUtils.getObject(this, PreferencesUtils.KEY_USER_INFO, UserBean.class);
        if (bean != null && StringUtils.isNotEmpty(bean.getTelephone())) {
            return bean.getTelephone();
        }
        return "";
    }


    public boolean isNeedUpdate() {
        UpgradeInfo upgradeInfo = Beta.getUpgradeInfo();
        if (upgradeInfo != null && upgradeInfo.versionCode > CommonUtils.getVersionCode(this)) {
            Log.i(TAG, "isNeedUpdate " + upgradeInfo.toString());
            return true;
        }
        return false;
    }

    /**
     * Socket 处理广播
     * @param action    ACTION
     * @param message   发送内容
     */
    public void sendBroadcast(@NonNull String action, String message){
        Intent intent = new Intent(action);
        intent.putExtra("Message",message);
        sendBroadcast(intent);
    }

    public void sendBroadcast(@NonNull String action){
        sendBroadcast(new Intent(action));
    }


    private DaemonClient mDaemonClient;

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        android.util.Log.i(TAG, "attachBaseContext");
        mDaemonClient = new DaemonClient(createDaemonConfigurations());
        mDaemonClient.onAttachBaseContext(base);
    }

    private DaemonConfigurations createDaemonConfigurations() {
        DaemonConfigurations.DaemonConfiguration configuration1 = new DaemonConfigurations.DaemonConfiguration(
                "net.hzlj.rl.zhangjiajie:process1",
                MainService.class.getCanonicalName(),
                MainReceiver.class.getCanonicalName());
        DaemonConfigurations.DaemonConfiguration configuration2 = new DaemonConfigurations.DaemonConfiguration(
                "net.hzlj.rl.zhangjiajie:process2",
                DaemonService.class.getCanonicalName(),
                DaemonReceiver.class.getCanonicalName());
        DaemonConfigurations.DaemonListener listener = new MyDaemonListener();
        return new DaemonConfigurations(configuration1, configuration2, listener);
    }


    class MyDaemonListener implements DaemonConfigurations.DaemonListener {

        @Override
        public void onPersistentStart(Context context) {
            android.util.Log.i(TAG, "MyDaemonListener onPersistentStart ...");
        }

        @Override
        public void onDaemonAssistantStart(Context context) {
            android.util.Log.i(TAG, "MyDaemonListener onDaemonAssistantStart ...");
        }

        @Override
        public void onWatchDaemonDaed() {
            android.util.Log.i(TAG, "MyDaemonListener onWatchDaemonDaed ...");
        }
    }
}
